var cron = require("cron");

//全局变量保存所有定时任务，注意开启多进程时内存同步问题
if (!global.tasks) {
    global.tasks = Object.create(null);
}

module.exports = {
    add: function (name, cronTime, onTick, onComplete, timezone) {
        global.tasks[name] = new cron.CronJob(cronTime, onTick, onComplete, false, timezone || 'Asia/Chongqing');
    },

    remove: function (name) {
        if (global.tasks[name]) {
            this.stop(name);
            delete global.tasks[name];
        }
    },

    removeAll: function () {
        global.tasks = Object.create(null);
    },

    start: function (taskOrName) {
        var task = this.getTask(taskOrName);
        task.start();
    },

    stop: function (taskOrName) {
        var task = this.getTask(taskOrName);
        task.stop();
    },

    startAll: function () {
        for (var name in global.tasks) {
            global.tasks[name].start();
        }
    },

    stopAll: function () {
        for (var name in global.tasks) {
            global.tasks[name].stop();
        }
    },

    setCronTime: function (taskOrName, cronTime, timezone) {
        var task = this.getTask(taskOrName);
        task.setTime(cron.time(cronTime, timezone || 'Asia/Chongqing'));
    },

    getTask: function (taskOrName) {
        var task;
        if (typeof taskOrName === 'string') {
            task = global.tasks[taskOrName];
        } else {
            task = taskOrName;
        }
        return task;
    }
};